﻿using Furion.LinqBuilder;
using Furion.Logging.Extensions;
using OAS.Application.AttendanceApp.Services;
using OAS.Application.AuthApp.Services;
using OAS.Application.MenuApp.Dtos;
using OAS.Application.MenuApp.Services;
using OAS.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace OAS.Application.MenuApp.Services
{
    public class MenuService : Repository<Menu>, IMenuService, ITransient
    {
        private readonly IAuthService _authService;
        public MenuService(IAuthService authService)
        {
            _authService = authService;
        }
        public async Task<List<DtoMenu>> GetMenuList()
        {
            var auths = await _authService.GetAuthList();
            var ids = auths.Where(o => o.Department_Id == UserContext.CurrentUser.Department_Id).Select(o => o.Menu_Id).ToList();
            Expression<Func<Menu, bool>> sqlWhere = o => true;
            sqlWhere = sqlWhere.AndIf(UserContext.CurrentUser.RoleName != "总经理" && !UserContext.IsAdmin, o => ids.Contains(o.MenuId));
            var menus = await AsQueryable().Where(sqlWhere).ToListAsync();
            var firstMenu = menus.Where(o => o.ParentId == null).OrderBy(o => o.SortIndex).Select(o => new DtoMenu
            {
                MenuId = o.MenuId,
                Path = o.MenuPath,
                Redirect = o.Redirect,
                Meta = new Meta
                {
                    Title = o.MenuName,
                    Icon = o.Icon
                },
                AlwaysShow = o.AlwaysShow == 1,
                SortIndex = o.SortIndex,
                Children = menus.Where(p => p.ParentId == o.MenuId).OrderBy(p=>p.SortIndex).Select(o => new DtoMenuChild
                {
                    MenuId = o.MenuId,
                    Path = o.MenuPath,
                        Meta = new Meta
                        {
                            Title = o.MenuName,
                            Icon = o.Icon,
                            HideClose = o.HideClose == 1,
                        },
                        Component = o.Component,
                        SortIndex = o.SortIndex,
                }).ToList()
            }).ToList();
            return firstMenu;
        }
        public async Task AddMenu(Menu menu)
        {
            if (base.AsQueryable().Any(o => o.MenuPath == menu.MenuPath)) throw Oops.Oh("该菜单路径已存在");
            await base.InsertAsync(menu);
        }
        public async Task UpdateMenu(Menu menu)
        {
            await base.AsUpdateable(menu).UpdateColumns(o => new { o.MenuName, o.Icon, o.SortIndex }).ExecuteCommandAsync();
        }
        public async Task DeleteMenu(Menu menu)
        {
            await base.DeleteAsync(menu);
        }
    }
}
